package com.easy.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.easy.bean.DataBranch;
import com.easy.bean.DataStructure;
import com.easy.enums.EasyJenkinsEnum;
import com.easy.util.PreferencesJenkinsUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 武天
 * @date 2022/12/5 10:25
 */
@Service
public class DataBranchService {

    public List<DataBranch> getDataBranchs(DataStructure dataStructure){
        try {
            String path = dataStructure.getDataPath()+"\\branch";
            if (StrUtil.isNotBlank(path)){
                String json = FileUtil.readUtf8String(path+"\\branch.jenkins");
                if(json.contains("{")){
                    List<DataBranch> branches = JSONObject.parseArray(json,DataBranch.class);
                    return branches;
                }else{
                    return new ArrayList<>();
                }

            }else {
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }

    public void setDataBranch(List<DataBranch> dataBranchs,DataStructure dataStructure){
        String path = dataStructure.getDataPath()+"\\branch";
        if (StrUtil.isNotBlank(path)){
            String jsonFormatString = JSON.toJSONString(dataBranchs, SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);
            FileUtil.writeUtf8String(jsonFormatString,path+"\\branch.jenkins");
        }
    }
}
